import Vue from 'vue'
import Vuex from 'vuex'
import {getAdminInfo} from '@/api/getData'

Vue.use(Vuex)

const state = {
	adminInfo: {
		avatar: 'default.jpg'
	},
	allTabs:[],
	activeTab:'/index',
	isTabs( tabs){
		console.log(this)
		/* 判断是否存在这个路由 */
		for (let i = 0; i < this.tabs.length; i++) {
			if (this.tabs[i].href == tabs.href) {
				// this.activeTab = href;
				// this.$router.push(href);
				return true;
			}
		}
		return false
	},
}
// var isTabs = function(state, tabs){
// 		/* 判断是否存在这个路由 */
// 		for (let i = 0; i < state.tabs.length; i++) {
// 			if (state.tabs[i].href == tabs.href) {
// 				// state.activeTab = href;
// 				// this.$router.push(href);
// 				return true;
// 			}
// 			return false;
// 		}
// 	}
const mutations = {
	saveAdminInfo(state, adminInfo){
		state.adminInfo = adminInfo;
	},
	addTabs(state, tabs){ 
		var title = tabs.title
		var href = tabs.href
		
		/* 判断是否存在这个路由 */
		for (let i = 0; i < state.allTabs.length; i++) {
			if (state.allTabs[i].href == tabs.href) {
				state.activeTab = href;
				// this.$router.push(href);
				return true;
			}
		}

		state.allTabs.push({
			href: href,
			title: title
		});
		state.activeTab = href;
	},
	setActiveTab(state, href){
		state.activeTab = href;
	},
	removeTabs(state, [index,name]){
		// a为tab的name
		// let index = 0;
		// let name = a;
		// for (var i = 0; i < this.allTabs.length; i++) {
		// 	if (this.allTabs[i].href == a) {
		// 		index = i;
		// 		break;
		// 	}
		// }
		console.log('name',name)
		/* 取得所在位置，然后删除 */
		state.allTabs.splice(index, 1);

		/* 判断当前关闭的是否为activeTab */
		if (state.activeTab == name) {
			if (state.allTabs.length > 0) {
				/* 让前一个成为activeTab,首先得到上一个tab的href */
				let href = state.allTabs[index - 1].href;
				console.log('href',href);
				
				state.activeTab = href;
				// state.$router.push(href);
			} else {
				state.activeTab = '/manage';
				// state.$router.push('/manage');
			}
		}else{

		}
	},

	isTabs(state, tabs){
		/* 判断是否存在这个路由 */
		for (let i = 0; i < state.tabs.length; i++) {
			if (state.tabs[i].href == tabs.href) {
				// state.activeTab = href;
				// this.$router.push(href);
				return true;
			}
			return false;
		}
	}
}

const actions = {
	async getAdminData({commit}){
		try{
			const res = await getAdminInfo()
			if (res.status == 1) {
				commit('saveAdminInfo', res.data);
			}else{
				throw new Error(res)
			}
		}catch(err){
			console.log('您尚未登陆或者session失效')
		}
	},
	removeTabs({commit},aaa){
		console.log('aaa',aaa);
		
		commit('removeTabs', aaa);
	},
	addTabs({commit},aaa){
		console.log('addTabs',aaa);
		commit('addTabs', aaa);
	},
	setActiveTab({commit},aaa){
		console.log('setActiveTab',aaa);
		commit('setActiveTab', aaa);
	}
}
const getters= {
	// ...
	getActiveTab: (state, getters) => {
		return state.activeTab
	},
	getAllTabs: (state, getters) => {
		return state.allTabs
	}
}
export default new Vuex.Store({
	state,
	getters,
	actions,
	mutations,
})